package com.it.ems.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                // 允许静态资源访问
                .requestMatchers("/css/**", "/js/**", "/images/**", "/webjars/**", "/static/**").permitAll()
                .requestMatchers("/login", "/register").permitAll()
                // 只有ADMIN角色可以访问仪表盘
                .requestMatchers("/dashboard").hasRole("ADMIN")
                // 允许所有认证用户访问寄件页面、我的收件页面和我的寄件页面
                .requestMatchers("/orders/send", "/orders/received", "/orders/sent").authenticated()
                // 允许所有认证用户访问订单详情、签收等功能（更具体的路径要在前面）
                .requestMatchers("/orders/details/**", "/orders/sign-for/**", "/orders/cancel/**", "/orders/track/**").authenticated()
                // 允许所有认证用户访问个人信息页面
                .requestMatchers("/profile").authenticated()
                // 只有ADMIN角色可以访问管理页面和订单管理（通用路径在后面）
                .requestMatchers("/orders/**", "/packages/**", "/users/**", "/addresses/**").hasRole("ADMIN")
                // 其他所有未明确配置的请求都需要认证
                .anyRequest().authenticated()
            )
            .formLogin(form -> form
                .loginPage("/login")
                .defaultSuccessUrl("/orders/send", true)
                .failureUrl("/login?error")
                .permitAll()
            )
            .logout(logout -> logout
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login?logout")
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID")
                .permitAll()
            );
        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}